package com.cje.login;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: ChenJinEn
 * @Date: 2020/8/9 19:41
 * @Description: //TODO 过滤器,过滤一切,包括方法请求和静态资源
 */
@WebFilter(initParams = {@WebInitParam(name = "encoding",value = "utf-8")})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器在处理任务");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //登录时不做拦截,以及静态资源不拦截
        if (request.getRequestURL().toString().contains("/Login") ||request.getRequestURL().toString().contains("/static")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        //注册时候不拦截
        if (request.getRequestURL().toString().contains("/Register")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        //退出登录不拦截
        if (request.getRequestURL().toString().contains("/LoginOut")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }

        //其他根据条件拦截
        if (request.getSession().getAttribute("user") != null) {
            //session中或者redis中存有用户信息,放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //转发到登录页面去登录
            request.getRequestDispatcher("/WEB/jsp/login.jsp").forward(request, response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("过滤器在销毁");
    }
}
